//
//  YSZUserAccount.swift
//  swiftweibo6
//
//  Created by ysz on 15/11/25.
//  Copyright © 2015年 user. All rights reserved.
//

import UIKit

class YSZUserAccount: NSObject, NSCoding
{
    
    class var userLogin: Bool {
        get{
            return YSZUserAccount.loadUserAccount() != nil
        }
    }
    //生命周期
    var expiresDate:NSDate?
    //授权用户的id
    var uid: String?
    
    //接口授权后的access_token
    var access_token: String?
    //用户名称
    var screen_name: String?
    //用户头像
    var avatar_large: String?
    
    var expires_in : Double = 0
    {
        didSet{
            //设置过期时间
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //字典转模型
    init(dict: [String: AnyObject])
    {
        super.init()
        //KVC 字典转模型
        setValuesForKeysWithDictionary(dict)
    }
    //加载用户信息
    func loadUserInfo()
    {
        YSZNetworkTools.shardInsatance.loadUserInfo { (result, error) -> () in
            if error != nil && result == nil
            {
                return
            }
            print("加载数据成功")
            self.screen_name = result!["screen_name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            YSZUserAccount.userAccount = self
            self.saveAccount()
        }
    }
    
    
    
    
    //保存路径 static 也可以访问   ／／类名.属性
    static let plistpath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!+"/account.plist"
    //保存账户信息到沙盒
    func saveAccount()
    {
        //归档 当前类
        NSKeyedArchiver.archiveRootObject(self, toFile: YSZUserAccount.plistpath)
    }
    //内存中的帐户
    private static var userAccount: YSZUserAccount?
    //读取保存在沙盒的账户信息
    class func loadUserAccount() -> YSZUserAccount?
    {
        if userAccount == nil
        {
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(plistpath) as? YSZUserAccount
            print("从沙盒加载")
        }
        else
        {
            print("从内存加载")
        }
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending
        {
            return userAccount
        }
//        //解档，如果有对象则判断是否过期
//        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(plistpath) as? YSZUserAccount
//        {
//            //判断是否过期
//            /*
//            compare 返回值是 NSComparisonResult 类型
//            OrderedAscending: 升序, 左边的比右边的小  <
//            OrderedSame:    相等, 左边等于右边   =
//            OrderedDescending: 降序,左边的比右边的大  >
//            */
//            
//        }
        return nil
    }
    //解档
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    //当KVC字典的key在模型中找不到对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print("\(key)")
    }
    
    /// 打印对象信息
    override var description: String {
        let properties=[ "access_token","expires_in","uid","expiresDate"]
        return "\(dictionaryWithValuesForKeys(properties))"
        
    }
    
}
